#!/bin/sh

harakiri() {
    printf "!!! %s !!!\n" "$*" &
    exit 1
}

prepare() {
    [ "$(id -u)" = 0 ] && harakiri "Don't go super sayan on this script! >.<"
    [ ! -f "booty.conf" ] && harakiri "Config file booty.conf not found, baka!"

    # shellcheck source=/dev/null
    . ./booty.conf

    [ -z "$UPDATECMD" ] && harakiri "Undefined repo update command!"
    printf "About to update main repo...\n"
    $UPDATECMD

    [ -z "$PACMAN" ] && harakiri "Pacman install command undefined!"
    [ -z "$AUR" ] && harakiri "Aur helper install command undefined!"
    [ -z "$GIT" ] && harakiri "Git command undefined!"

    [ -z "$PROGFILES" ] && harakiri "No progfiles defined!"
    printf "These progfiles were defined: %s\n" "$PROGFILES"
}

read_prog_files() {
    printf "%s\n" "$PROGFILES" | tr ' ' '\n' | while read -r file; do
        printf "Processing %s...\n" "$file"
        if [ -f "$file" ]; then
            process_prog_file "$file"
        else
            printf "Couldn't find %s. Skipping to next file if any.\n" "$file"
        fi
    done
}

process_prog_file() {
    FNAME=$(printf "%s" "$1" | cut -d. -f1)
    while IFS= read -r program; do
        case "$FNAME" in
        "base") $PACMAN "$program" ;;
        "pacman") $PACMAN "$program" ;;
        "aur") $AUR "$program" ;;
        "git") process_git "$program" ;;
        *) printf "Undefined install command. Skipping...\n" ;;
        esac

    done <"$1"
}

process_git() {
    folder_name="/tmp/$(printf "%s" "$1" | sed -e 's/[\/.:-]//g')"
    $GIT "$1" "$folder_name"
}

prepare
read_prog_files
